package com.jy.modules.cims.deal.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.jsoup.helper.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.controller.CimsBaseController;
import com.jy.modules.cims.common.controller.ExportController;
import com.jy.modules.cims.common.exception.CimsException;
import com.jy.modules.cims.common.exception.CimsExceptionConstant;
import com.jy.modules.cims.common.sysUtils.CollectionsUtils;
import com.jy.modules.cims.common.sysUtils.DateTimeUtils;
import com.jy.modules.cims.common.sysUtils.ExceptionUtils;
import com.jy.modules.cims.common.sysUtils.PropertyUtil;
import com.jy.modules.cims.common.sysUtils.SearchParamUtil;
import com.jy.modules.cims.common.sysUtils.SimpleStringUtils;
import com.jy.modules.cims.common.sysUtils.SpringContextUtils;
import com.jy.modules.cims.component.common.service.TCMmCooperorgDealService;
import com.jy.modules.cims.component.common.service.TCMmCreditPackageService;
import com.jy.modules.cims.component.image.service.AddWaitDealQueueService;
import com.jy.modules.cims.component.loan.CLoanImpl;
import com.jy.modules.cims.component.quota.ICQuota;
import com.jy.modules.cims.component.settle.CCimsFileOperImpl;
import com.jy.modules.cims.component.sysAssist.CSysAssistImpl;
import com.jy.modules.cims.contract.service.ContractService;
import com.jy.modules.cims.creditright.service.CreditRightService;
import com.jy.modules.cims.creditright.service.SettleCreditService;
import com.jy.modules.cims.data.common.dto.TCMmCooperorgDealDTO;
import com.jy.modules.cims.data.common.dto.TCMmCreditPackageDTO;
import com.jy.modules.cims.data.common.dto.TCMmLoanDetailDTO;
import com.jy.modules.cims.data.common.dto.TCMmQuotaLoanDetailDTO;
import com.jy.modules.cims.data.dto.ContractAllDto;
import com.jy.modules.cims.data.dto.CreditDetailDto;
import com.jy.modules.cims.data.dto.CreditDetailQueryDto;
import com.jy.modules.cims.data.dto.CreditRightDto;
import com.jy.modules.cims.data.dto.DealDto;
import com.jy.modules.cims.data.dto.Df02FileDto;
import com.jy.modules.cims.data.dto.DfHzContentDto;
import com.jy.modules.cims.data.dto.LoanDetailDto;
import com.jy.modules.cims.data.dto.LoanDto;
import com.jy.modules.cims.data.dto.QuotaCreditDetailDto;
import com.jy.modules.cims.data.dto.QuotaCreditRightDto;
import com.jy.modules.cims.data.dto.QuotaLoanDetailDto;
import com.jy.modules.cims.data.dto.QuotaLoanDto;
import com.jy.modules.cims.deal.service.DealService;
import com.jy.modules.cims.deal.service.LoanDealService;
import com.jy.modules.cims.loan.service.RaisePlanService;
import com.jy.modules.cims.quota.service.QuotaService;
import com.jy.modules.cims.loan.service.TBJLoanService;
import com.jy.platform.core.common.BaseDTO;
import com.jy.platform.core.message.DataMsg;
import com.jy.platform.core.message.PageParameter;
import com.jy.platform.core.message.PageUtil;
import com.jy.platform.core.message.QueryReqBean;

/**
 * 交易处理控制层
 */
@Controller
@Scope("prototype")
@RequestMapping("/cooperorgDeal")
public class DealController extends CimsBaseController {
	private static final Logger logger = LoggerFactory.getLogger(DealController.class);

	public DealController() {
	}

	@Autowired
	private SpringContextUtils springContextUtils;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.deal.service.DealService")
	public DealService dealService;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.deal.service.LoanDealService")
	public LoanDealService loanDealService;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.component.loan.CLoanImpl")
	public CLoanImpl loanImpl;

	// 额度申请服务
	@Autowired
	@Qualifier("com.jy.modules.cims.quota.service.QuotaService")
	public QuotaService quotaService;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.contract.service.ContractService")
	public ContractService contractService;

	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmCooperorgDealService")
	private TCMmCooperorgDealService cooperorgDealService;

	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmCreditPackageService")
	private TCMmCreditPackageService creditPackageService;

	@Autowired
	@Qualifier("com.jy.modules.cims.component.quota.CQuotaImpl")
	private ICQuota iCQuota;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.component.sysAssist.CSysAssistImpl")
	private CSysAssistImpl csysAssistimpl;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.component.settle.CCimsFileOperImpl")
	private CCimsFileOperImpl fileOperImpl;

	@Autowired
	@Qualifier("com.jy.modules.cims.creditright.service.SettleCreditService")
	private SettleCreditService settleCreditService;

	@Autowired
	@Qualifier("com.jy.modules.cims.creditright.service.CreditRightService")
	private CreditRightService creditRightService;

	/**
	 * 募集计划操作
	 */
	@Autowired
	@Qualifier("com.jy.modules.cims.loan.service.RaisePlanService")
	private RaisePlanService raisePlanService;

	@Autowired
	@Qualifier("com.jy.modules.cims.loan.service.TBJLoanService")
	private TBJLoanService tBJLoanService;
	
	
	/**
	 * @author dell
	 * @description:查询分页列表(操作交易流水表)
	 * @date 2015-01-07 10:50:50
	 * @param request
	 * @param dto
	 * @param dataMsg
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getDealCreditList")
	@ResponseBody
	public DataMsg getDealCreditList(HttpServletRequest request, DealDto dto, @ModelAttribute DataMsg dataMsg) {
		dto.setDealType(CimsConstant.DEAL_TYPE_CREDIT_OUT);
		getDealCreditListByType(request, dto, dataMsg);
		return dataMsg;
	}

	/**
	 * 查询月还交易流水(操作交易流水表)
	 * 
	 * @Title getDealCreditListByMonthSettle
	 * @Description TODO
	 * @param request
	 * @param dto
	 * @param dataMsg
	 * @return DataMsg
	 * @author lizhiqiang
	 * @date 2015-3-31-下午5:48:20
	 * @update
	 * @throws
	 */
	@RequestMapping(value = "/getDealCreditListByMonthSettle")
	@ResponseBody
	public DataMsg getDealCreditListByMonthSettle(HttpServletRequest request, DealDto dto, @ModelAttribute DataMsg dataMsg) {
		getDealCreditListByType(request, dto, dataMsg);
		return dataMsg;
	}

	/**
	 * 查询交易流水(操作交易流水表)
	 * 
	 * @Title getDealCreditListByType
	 * @Description TODO
	 * @param request
	 * @param dto
	 * @param dataMsg
	 *            void
	 * @author lizhiqiang
	 * @date 2015-3-31-下午5:47:54
	 * @update
	 * @throws
	 */
	private void getDealCreditListByType(HttpServletRequest request, DealDto dto, DataMsg dataMsg) {
		Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("dto", dto);
		QueryReqBean params = new QueryReqBean();
		params.setSearchParams(searchParams);
		PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);

		List<DealDto> list = dealService.getDealList(params.getSearchParams());

		dataMsg.setData(list);
		dataMsg.setTotalRows(pageInfo.getTotalCount());
	}

	/**
	 * @author dell
	 * @description:查询分页列表(操作交易流水表)
	 * @date 2015-01-07 10:50:50
	 * @param request
	 * @param dto
	 * @param dataMsg
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getDealCreditListByIds")
	@ResponseBody
	public DataMsg getDealCreditListByIds(HttpServletRequest request, @ModelAttribute DataMsg dataMsg) {
		Map<String, Object> dto = new HashMap<String, Object>();
		String ids = this.getParameterString("id");
		dto.put("ids", ids == null ? new String[] { "000" } : ids.split(","));
		List<DealDto> list = dealService.getDealListByIds(SearchParamUtil.getSearchParam(dto));
		dataMsg.setData(list);
		return dataMsg;
	}

	/**
	 * @author dell
	 * @description:查询分页列表(操作交易流水表)
	 * @date 2015-01-07 10:50:50
	 * @param request
	 * @param dto
	 * @param dataMsg
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getDealLoanList")
	@ResponseBody
	public DataMsg getDealLoanList(HttpServletRequest request, DealDto dto, @ModelAttribute DataMsg dataMsg) {
		Map<String, Object> searchParams = new HashMap<String, Object>();
		dto.setDealType(CimsConstant.DEAL_TYPE_LOAN_OUT);
		searchParams.put("dto", dto);
		QueryReqBean params = new QueryReqBean();
		params.setSearchParams(searchParams);
		PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);

		List<DealDto> list = dealService.getDealList(params.getSearchParams());

		dataMsg.setData(list);
		dataMsg.setTotalRows(pageInfo.getTotalCount());
		return dataMsg;
	}

	/**
	 * @author dell
	 * @description:报盘管理查询分页列表(操作交易流水表)
	 * @date 2015-01-07 10:50:50
	 * @param request
	 * @param dto
	 * @param dataMsg
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getDealLoanListByoffer")
	@ResponseBody
	public DataMsg getDealLoanListByoffer(HttpServletRequest request, DealDto dto, @ModelAttribute DataMsg dataMsg) {
		Map<String, Object> searchParams = new HashMap<String, Object>();

		// 02:在途; 06:我司拒绝放款
		String dealStatusStr = SimpleStringUtils.append(" '", CimsConstant.DEAL_STATUS_WAY, "' ,'", CimsConstant.DEAL_STATUS_FUNDOUT_LOSE_M, "' ,'",CimsConstant.DEAL_STATUS_FINISH, "' ");
		dto.setDealStatusStr(dealStatusStr);

		dto.setDealType(CimsConstant.DEAL_TYPE_LOAN_OUT);// 03: 贷款转出
		searchParams.put("dto", dto);
		QueryReqBean params = new QueryReqBean();
		params.setSearchParams(searchParams);
		PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
		List<DealDto> list = dealService.getDealList(params.getSearchParams());
		dataMsg.setData(list);
		dataMsg.setTotalRows(pageInfo.getTotalCount());

		searchParams = null;

		return dataMsg;
	}

	/**
	 * @description 交易流水债权明细查询列表(操作债权交易明细、债权明细、客户信息)
	 * @param request
	 * @param response
	 * @param result
	 */
	@RequestMapping(value = "/getDealDetailByCreditList")
	@ResponseBody
	public DataMsg getDealDetailByCreditList(HttpServletRequest request, DealDto dto, @ModelAttribute DataMsg dataMsg) throws Exception {
		Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("dto", dto);
		QueryReqBean params = new QueryReqBean();
		params.setSearchParams(searchParams);
		PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
		List<CreditDetailDto> list = dealService.getDealDetailByCreditList(params.getSearchParams());
		
		List<CreditDetailDto> result = new ArrayList<CreditDetailDto>();
		if (CollectionsUtils.isNotEmpty(list)) {
			for(CreditDetailDto  creditDetailDto : list){
				result.add(creditDetailDto);
			}	
		}
		dataMsg.setData(result);
		dataMsg.setTotalRows(pageInfo.getTotalCount());

		return dataMsg;
	}

	/**
	 * @description 交易流水债权明细查询列表(操作贷款明细、客户信息)
	 * @param request
	 * @param response
	 * @param result
	 */
	@RequestMapping(value = "/getDealDetailByLoanList")
	@ResponseBody
	public DataMsg getDealDetailByLoanList(HttpServletRequest request, DealDto dto, @ModelAttribute DataMsg dataMsg) throws Exception {
		try {
			Map<String, Object> searchParams = new HashMap<String, Object>();
			TCMmLoanDetailDTO loanDetailDTO = new TCMmLoanDetailDTO();
			loanDetailDTO.setDealCode(dto.getDealCode());
			searchParams.put("dto", loanDetailDTO);
			QueryReqBean params = new QueryReqBean();
			params.setSearchParams(searchParams);
			PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
			params.setPageParameter(pageInfo);
			List<LoanDetailDto> list = loanDealService.getDealDetailByLoanList(params.getSearchParams());
			dataMsg.setData(list);
			dataMsg.setTotalRows(pageInfo.getTotalCount());
		} catch (Exception e) {
			dataMsg.failed(ExceptionUtils.getStackTraceAsString(e));
		}
		return dataMsg;
	}

	/**
	 * @description 交易流水债权明细查询列表(操作债权交易明细、债权明细)
	 * @param request
	 * @param response
	 * @param result
	 */
	@RequestMapping(value = "/getDealDetailByCreditTotal")
	@ResponseBody
	public DataMsg getDealDetailByCreditTotal(HttpServletRequest request, DealDto dto, @ModelAttribute DataMsg dataMsg) throws Exception {
		String dealCode = dto.getDealCode();
		logger.info("交易流水::" + dealCode);
		CreditRightDto creditRightDto = new CreditRightDto();
		Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("dto", dto);
		QueryReqBean params = new QueryReqBean();
		params.setSearchParams(searchParams);
		PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
		List<CreditDetailDto> creditDetailList = dealService.getDealDetailByCreditList(params.getSearchParams());
		List<DealDto> dealList = dealService.getCooperorgDealByDealCodeStr(dto.getDealCode());
		if (null != dealList) {
			BigDecimal sumCreditorValue = dealList.get(0).getSumCreditorValue();
			if (null == sumCreditorValue) {
				CreditRightDto temp = dealService.getDealDetailByCreditListByTotal(params.getSearchParams());
				if (null != temp) {
					sumCreditorValue = temp.getSumCreditorValue();
				}
			}

			creditRightDto.setSumCreditorValue(sumCreditorValue);
		}
		if (null != creditDetailList) {
			creditRightDto.setDetialNumber(new BigDecimal(pageInfo.getTotalCount()));
		}

		dataMsg.setData(creditRightDto);
		return dataMsg;
	}

	/**
	 * @description 交易流水债权明细查询列表(操作债权交易明细、债权明细)
	 * @param request
	 * @param response
	 * @param result
	 */
	@RequestMapping(value = "/getDealDetailByCreditSumTotal")
	@ResponseBody
	public DataMsg getDealDetailByCreditSumTotal(HttpServletRequest request, DealDto dto, @ModelAttribute DataMsg dataMsg) throws Exception {
		String dealCode = dto.getDealCode();
		logger.info("交易流水::" + dealCode);
		Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("dto", dto);
		QueryReqBean params = new QueryReqBean();
		params.setSearchParams(searchParams);
		CreditRightDto creditRightDto = dealService.getDealDetailByCreditListByTotal(params.getSearchParams());
		dataMsg.setData(creditRightDto);
		return dataMsg;
	}
	
	
	/**
	 * @description 交易流水债权明细查询列表(操作债权交易明细、债权明细)
	 * @param request
	 * @param response
	 * @param result
	 ** @throws
	 * @author 周鹏
	 * @date 2016-4-14
	 */
	@RequestMapping(value = "/getDealDetailByFeeSum")
	@ResponseBody
	public DataMsg getDealDetailByFeeSum(HttpServletRequest request, DealDto dto, @ModelAttribute DataMsg dataMsg) throws Exception {
		String dealCode = dto.getDealCode();
		logger.info("交易流水::" + dealCode);
		Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("dealCode", dealCode);
		QueryReqBean params = new QueryReqBean();
		params.setSearchParams(searchParams);
		DealDto dealFeeDto = dealService.getDealStream(params.getSearchParams());
		dataMsg.setData(dealFeeDto);
		return dataMsg;
		
	}
	

	/**
	 * 删除债权交易明细信息(操作债权交易明细、债权明细-调用释放债权的接口)
	 * 
	 * @param request
	 * @param response
	 * @param result
	 * @throws Exception
	 */
	@RequestMapping(value = "/deleteDetailByCredit")
	@ResponseBody
	public DataMsg deleteDetailByCredit(HttpServletRequest request, @ModelAttribute DataMsg dataMsg) {
		BaseDTO dto = super.initDto(null);
		String transferIds = (String) this.getParameter("transferIds");// 格式:1,2,3
		// String dealStatus = (String)
		// this.getParameter("cooperativeAgencyDealStatus");// 合作机构交易状态
		String dealCode = (String) this.getParameter("dealCode");// 合作机构交易状态
		dataMsg = super.initDataMsg(dataMsg);
		try {
			dealService.confirmRemoveDetailByCredit(dto, transferIds, dealCode);
			dataMsg.setMsg("删除成功");
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			throw new CimsException(e.getMessage());
		}
		return dataMsg;
	}

	/**
	 * 删除贷款交易明细信息(操作贷款明细-调用贷款释放接口)
	 * 
	 * @param request
	 * @param response
	 * @param result
	 */
	@RequestMapping(value = "/deleteDetailByLoan")
	@ResponseBody
	public DataMsg deleteDetailByLoan(HttpServletRequest request, @ModelAttribute DataMsg dataMsg) {
		BaseDTO dto = super.initDto(null);
		String intoAppCodes = (String) this.getParameter("intoAppCodes");// 格式:1,2,3
		String contractNos = (String) this.getParameter("contractNos");
		dataMsg = super.initDataMsg(dataMsg);
		try {
			dealService.doConfirmRemoveDetailByLoan(dto, contractNos, intoAppCodes);
			dataMsg.setMsg("删除成功");
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("执行方法dealService.confirmRemoveDetailByLoan异常：", ExceptionUtils.getStackTraceAsString(e));
			throw new CimsException(e.getMessage());
		}
		return dataMsg;
	}

	/**
	 * @description 根据页面选择多个贷款明细id拒绝放款
	 * @param request
	 * @param response
	 * @param result
	 */
	@RequestMapping(value = "/refusedLendByLoanDetailIds")
	@ResponseBody
	public DataMsg refusedLendByLoanDetailIds(HttpServletRequest request, @ModelAttribute DataMsg dataMsg) {
		initDto(null);
		String ids = (String) this.getParameter("ids");// 格式:1,2,3
		dataMsg = super.initDataMsg(dataMsg);
		String resultstr = null;
		try {
			resultstr = loanDealService.doRefusedLendByLoanDetailIds(ids);
			dataMsg.setStatus("ok");
			dataMsg.setMsg(resultstr);
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("执行方法loanDealService.doRefusedLendByLoanDetailIds异常：", ExceptionUtils.getStackTraceAsString(e));
			throw new CimsException(e.getMessage());
		}
		return dataMsg;
	}

	/**
	 * @description 根据页面选择多个交易流水id拒绝放款
	 * @param request
	 * @param response
	 * @param result
	 */
	@RequestMapping(value = "/refusedLendByDealIds")
	@ResponseBody
	public DataMsg refusedLendByDealIds(HttpServletRequest request, @ModelAttribute DataMsg dataMsg) {
		initDto(null);

		String ids = (String) this.getParameter("ids");// 格式:1,2,3

		dataMsg = super.initDataMsg(dataMsg);
		String resultstr = null;
		try {
			resultstr = loanDealService.doRefusedLendByDealIds(ids);
			
			dataMsg.setStatus("ok");
			dataMsg.setMsg(resultstr);
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("执行方法loanDealService.doRefusedLendByDealIds异常：", ExceptionUtils.getStackTraceAsString(e));
			throw new CimsException(e.getMessage());
		}
		return dataMsg;
	}

	/**
	 * 删除交易流水表,包含贷款和债权(操作交易流水表、债权交易明细、债权明细、贷款明细-调用债权释放接口、贷款释放接口)
	 * 
	 * @param request
	 * @param response
	 * @param result
	 */
	@RequestMapping(value = "/deleteDeal")
	@ResponseBody
	public DataMsg deleteDeal(HttpServletRequest request, @ModelAttribute DataMsg dataMsg) {
		super.initDto(null);
		String ids = (String) this.getParameter("ids");// 格式: 1,2,3
		dataMsg = super.initDataMsg(dataMsg);
		try {
			dataMsg = dealService.confirmDoDeleteDeal(ids,dataMsg);
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("执行方法dealService.confirmDoDeleteDeal异常：", ExceptionUtils.getStackTraceAsString(e));
			throw new CimsException(e.getMessage());
		}
		return dataMsg;
	}

	/**
	 * 查询额度申请的贷款明细(操作额度申请贷款明细表)
	 */
	@RequestMapping(value = "/getQuotaDetailByLoan")
	@ResponseBody
	public DataMsg getQuotaDetailByLoan(HttpServletRequest request, QuotaLoanDetailDto dto, @ModelAttribute DataMsg dataMsg) throws Exception {
		String repayDay  = request.getParameter("repayDay");
		Map<String, Object> searchParams = new HashMap<String, Object>();
		dto.setDealStatus(CimsConstant.QUOTA_DETAIL_STATUS_NEW);
		dto.setRepayDay(repayDay);
		searchParams.put("dto", dto);
		QueryReqBean params = new QueryReqBean();
		params.setSearchParams(searchParams);
		PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
		List<TCMmQuotaLoanDetailDTO> list = quotaService.getQuotaLoanDetailByPaging(params.getSearchParams());
		dataMsg.setData(list);
		dataMsg.setTotalRows(pageInfo.getTotalCount());
		return dataMsg;
	}

	/**
	 * 统计交易流水对应的贷款明细条数(操作贷款明细表)
	 * 
	 * @param request
	 * @param response
	 * @param result
	 */
	@RequestMapping(value = "/getDealDetailByLoanTotal")
	@ResponseBody
	public DataMsg getDealDetailByLoanTotal(HttpServletRequest request, DealDto dto, @ModelAttribute DataMsg dataMsg) throws Exception {
		Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("dto", dto);
		QueryReqBean params = new QueryReqBean();
		params.setSearchParams(searchParams);
		LoanDto loanDto = dealService.getDealDetailByLoanListByTotal(params.getSearchParams());
		dataMsg.setData(loanDto);
		return dataMsg;
	}

	/**
	 * 功能说明：从贷款额度申请明细挑选贷款信息; 创建交易流水; 更新额度申请贷款信息交易状态，申请>>交易 ;
	 * (操作交易流水表、贷款明细表、额度申请贷款明细表)
	 */
	@RequestMapping(value = "/updateQuotaDetailByLoan")
	@ResponseBody
	public DataMsg updateQuotaDetailByLoan(HttpServletRequest request, QuotaLoanDto dto, @ModelAttribute DataMsg dataMsg) {
		try {
			dto = (QuotaLoanDto) super.initDto(dto);
			String dealCode = dto.getDealCode();
			String did = this.getParameterString("id");
			Long dealId = did == "" ? null : Long.valueOf(did);
			Date dealDate = new Date();
			if (StringUtil.isBlank(dto.getDealCode())) {
				// 创建交易流水信息
				DealDto dealDto = new DealDto();
				StringBuffer dealCodesb = new StringBuffer();
				quotaService.doGetDealCode(dealCodesb);
				dealCode = dealCodesb.toString();
				dealDto.setDealCode(dealCode);// 交易流水号
				dealDto.setCooperorgCode(dto.getCooperorgCode());
				dealDto.setContractCode(dto.getContractCode());// 合约编号
				dealDto.setCooperativeAgencyDealStatus(CimsConstant.DEAL_STATUS_CREATE);// 新建
				dealDto.setDealType(CimsConstant.DEAL_TYPE_LOAN_OUT);
				dealDto.setCreditPackageName(dto.getCreditPackageName());
				dealDto.setAgreementCode(dto.getAgreementCode());
				dealDto.setPlanId(dto.getPlanId());
				dealDto.setRepayType(dto.getRepayType());//还款方式
				if (dto.getRepayDay() != null && !"".equals(dto.getRepayDay())) {
					dealDto.setBillDate(Long.valueOf(dto.getRepayDay()));
					dealDto.setBillDateEnd(Long.valueOf(dto.getBillDateEnd()));
				}
				dealDto.setDealDate(dealDate);//交易日期
				dealId = cooperorgDealService.insertTCMmCooperorgDeal(dealDto);
			}
			
			//通过合约号获取合约相关信息
			ContractAllDto contractAllDto = contractService.getContractAllInfo(dto.getContractCode());
			if(contractAllDto!=null){
				dto.setProductType(contractAllDto.getCdto().getProductType());
			}
			
			//保存包信息
			TCMmCreditPackageDTO creditPackageDTO = creditRightService.getCreditPackageForUnique(dto.getCooperorgCode(),
					dto.getCreditPackageName(), dto.getContractCode());
			if (null == creditPackageDTO) {
				// 保存包信息
				creditPackageDTO = new TCMmCreditPackageDTO();
				creditPackageDTO.setCooperorgCode(dto.getCooperorgCode());// 机构编号
				creditPackageDTO.setContractCode(dto.getContractCode());// 合约编号
				creditPackageDTO.setCreditPackageName(dto.getCreditPackageName());// 包号
				creditPackageDTO.setBillDate(Long.parseLong(dto.getRepayDay()));
				creditPackageDTO.setBillDateEnd(Long.parseLong(dto.getBillDateEnd()));
				creditPackageDTO.setRepayType(dto.getRepayType());
				creditPackageService.insertTCMmCreditPackage(creditPackageDTO);
			}else{
				// 保存包信息 
				creditPackageDTO = new TCMmCreditPackageDTO();
				creditPackageDTO.setCooperorgCode(dto.getCooperorgCode());// 机构编号
				creditPackageDTO.setContractCode(dto.getContractCode());// 合约编号
				creditPackageDTO.setCreditPackageName(dto.getCreditPackageName());// 包号
				creditPackageDTO.setBillDate(Long.parseLong(dto.getRepayDay()));
				creditPackageDTO.setBillDateEnd(Long.parseLong(dto.getBillDateEnd()));
				creditPackageDTO.setRepayType(dto.getRepayType());
				creditPackageService.updateTCMmCreditPackageByPackageName(creditPackageDTO);
			}
			
			Map<String, Object> resultMap = new HashMap<String, Object>();
			resultMap.put("id", dealId);
			resultMap.put("dealCode", dealCode);
			resultMap.put("dealDate", DateTimeUtils.formatDate(dealDate, "yyyy-MM-dd"));
			
			TCMmCooperorgDealDTO dealdto = new TCMmCooperorgDealDTO();
			dealdto.setDealCode(dealCode);
			dealdto.setCooperorgCode(dto.getCooperorgCode());
			
			//获取包信息
			Map<String, Object> searchParams = new HashMap<String, Object>();
			TCMmCreditPackageDTO tCMmCreditPackageDTO = new TCMmCreditPackageDTO();
			tCMmCreditPackageDTO.setContractCode(dto.getContractCode());
			tCMmCreditPackageDTO.setCooperorgCode(dto.getCooperorgCode());
			tCMmCreditPackageDTO.setCreditPackageName(dto.getCreditPackageName());
	    	searchParams.put("dto", tCMmCreditPackageDTO);
	        List<TCMmCreditPackageDTO> list = creditPackageService.searchTCMmCreditPackage(searchParams);
	        
			
			if(list.size()>0){
				tCMmCreditPackageDTO =  list.get(0);
				if(null != tCMmCreditPackageDTO.getPlanRedeemDate()){
					dto.setPlanRedeemDate(tCMmCreditPackageDTO.getPlanRedeemDate());//计划赎回日期
				}
			}
			
			dealService.saveLoanDealDetail(dto, dealdto);
			
			
			dataMsg = super.initDataMsg(dataMsg);
			dataMsg.setMsg("添加成功");
			dataMsg.setData(resultMap);
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error(CimsExceptionConstant.SURE_LOAN_FAILED, ExceptionUtils.getStackTraceAsString(e));
		}
		return dataMsg;
	}

	/**
	 * 查询额度申请的债权明细
	 */
	@RequestMapping(value = "/getQuotaDetailByCredit")
	@ResponseBody
	public DataMsg getQuotaDetailByCredit(HttpServletRequest request, QuotaCreditRightDto dto, @ModelAttribute DataMsg dataMsg) throws Exception {

		dto.setDealStatus(CimsConstant.QUOTA_DETAIL_STATUS_NEW);
		Map<String, Object> searchParams = new HashMap<String, Object>();
		dto.setPackageNum(null);
		searchParams.put("dto", dto);
		QueryReqBean params = new QueryReqBean();
		params.setSearchParams(searchParams);
		PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
		List<QuotaCreditDetailDto> list = iCQuota.searchQuotaCreditDetailByPaging(params.getSearchParams());
		dataMsg.setData(list);
		dataMsg.setTotalRows(pageInfo.getTotalCount());
		return dataMsg;
	}

	/**
	 * 从额度申请债权明细挑选债权： 创建交易流水。 更新额度申请债权明细交易状态，申请>>交易 。 保存债权明细。
	 * 调用债权释放接口。(操作交易流水表、额度申请债权明细、债权明细、债权交易明细)
	 */
	@RequestMapping(value = "/updateQuotaDetailByCredit")
	@ResponseBody
	public DataMsg updateQuotaDetailByCredit(HttpServletResponse response, HttpServletRequest request, QuotaCreditRightDto dto,
			@ModelAttribute DataMsg dataMsg) {
		if (null == dto.getDealType()) {
			dataMsg.failed("传入参数值“交易类型”为空");
			logger.error("传入参数值“交易类型”为空");
			return dataMsg;
		}
		try {
			dto = (QuotaCreditRightDto) super.initDto(dto);
			String dealCode = dto.getDealCode();
			String did = this.getParameterString("id");
			Long dealId = !SimpleStringUtils.hasText(did) ? null : Long.valueOf(did);
			Date dealDate = new Date();
			if (StringUtil.isBlank(dto.getDealCode())) {
				// 创建交易流水信息
				DealDto dealDto = new DealDto();
				StringBuffer dealCodesb = new StringBuffer();
				dealService.doGetDealCode(dealCodesb);
				dealCode = dealCodesb.toString();
				dealDto.setDealCode(dealCode);// 交易流水号
				dealDto.setCooperorgCode(dto.getCooperorgCode());
				dealDto.setContractCode(dto.getContractCode());// 合约编号
				dealDto.setAgreementCode(dto.getArgeementCode());// 协议编号
				dealDto.setCooperativeAgencyDealStatus(CimsConstant.DEAL_STATUS_CREATE);// 新建
				dealDto.setDealType(dto.getDealType());// 交易类型
				dealDto.setBillDate(dto.getBillDate()); // 账单起始日
				dealDto.setBillDateEnd(dto.getBillDateEnd());// 账单结束日
				dealDto.setRepayType(dto.getRepayType());// 还款方式
				dealDto.setCreditPackageName(dto.getPackageNum()); // 包名
				dealDto.setDealDate(dealDate);
				dealId = cooperorgDealService.insertTCMmCooperorgDeal(dealDto);
			}
			
			
			//通过合约号获取合约相关信息
			ContractAllDto contractAllDto = contractService.getContractAllInfo(dto.getContractCode());
			if(contractAllDto!=null){
				dto.setProductType(contractAllDto.getCdto().getProductType());
			}
			
			//保存包信息
			TCMmCreditPackageDTO creditPackageDTO = creditRightService.getCreditPackageForUnique(dto.getCooperorgCode(),
					dto.getPackageNum(), dto.getContractCode());
			if (null == creditPackageDTO) {
				// 保存包信息
				creditPackageDTO = new TCMmCreditPackageDTO();
				creditPackageDTO.setCooperorgCode(dto.getCooperorgCode());// 机构编号
				creditPackageDTO.setContractCode(dto.getContractCode());// 合约编号
				creditPackageDTO.setCreditPackageName(dto.getPackageNum());// 包号
				creditPackageDTO.setBillDate(dto.getBillDate());
				creditPackageDTO.setBillDateEnd(dto.getBillDateEnd());
				creditPackageDTO.setRepayType(dto.getRepayType());
				creditPackageService.insertTCMmCreditPackage(creditPackageDTO);
			}else{
				// 保存包信息 
				creditPackageDTO = new TCMmCreditPackageDTO();
				creditPackageDTO.setCooperorgCode(dto.getCooperorgCode());// 机构编号
				creditPackageDTO.setContractCode(dto.getContractCode());// 合约编号
				creditPackageDTO.setCreditPackageName(dto.getPackageNum());// 包号
				creditPackageDTO.setBillDate(dto.getBillDate());
				creditPackageDTO.setBillDateEnd(dto.getBillDateEnd());
				creditPackageDTO.setRepayType(dto.getRepayType());
				creditPackageService.updateTCMmCreditPackageByPackageName(creditPackageDTO);
			}
			
			Map<String, Object> resultMap = new HashMap<String, Object>();
			resultMap.put("id", dealId);
			resultMap.put("dealCode", dealCode);
			resultMap.put("dealDate", DateTimeUtils.formatDate(dealDate, "yyyy-MM-dd"));
			// 保存挑选结果
			Map<String, Object> searchParams = new HashMap<String, Object>();
			TCMmCreditPackageDTO tCMmCreditPackageDTO = new TCMmCreditPackageDTO();
			tCMmCreditPackageDTO.setContractCode(dto.getContractCode());
			tCMmCreditPackageDTO.setCooperorgCode(dto.getCooperorgCode());
			tCMmCreditPackageDTO.setCreditPackageName(dto.getPackageNum());
	    	searchParams.put("dto", tCMmCreditPackageDTO);
	    	
	    	//获取包信息
	        List<TCMmCreditPackageDTO> list = creditPackageService.searchTCMmCreditPackage(searchParams);
	        
			TCMmCooperorgDealDTO dealdto = new TCMmCooperorgDealDTO();
			dealdto.setDealCode(dealCode);
			dealdto.setContractCode(dto.getContractCode());
			dealdto.setCooperorgCode(dto.getCooperorgCode());
			
			if(list.size()>0){
				tCMmCreditPackageDTO =  list.get(0);
				if(null != tCMmCreditPackageDTO.getPlanRedeemDate()){
					dto.setPlanRedeemDate(tCMmCreditPackageDTO.getPlanRedeemDate());//计划赎回日期
				}
			}
			
			String result = dealService.saveCreditDealDetail(dto, dealdto);

			dataMsg = super.initDataMsg(dataMsg);
			dataMsg.setMsg(result);
			dataMsg.setData(resultMap);
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error(CimsExceptionConstant.SURE_CREDIT_FAILED, ExceptionUtils.getStackTraceAsString(e));
		}
		return dataMsg;
	}

	/**
	 * @throws Exception
	 * @Title save
	 * @Description 保存交易流水表，创建债权包，更新债权或贷款的包号(操作交易流水表、债权包表、债权明细、贷款明细)
	 * @param request
	 * @param response
	 * @param result
	 * @author lizhiqiang
	 * @date 2015-1-20-上午9:45:29
	 * @update
	 * @throws
	 */
	@RequestMapping(value = "/saveCooperorgDeal")
	@ResponseBody
	public DataMsg save(HttpServletRequest request, DealDto dto, @ModelAttribute DataMsg dataMsg) throws Exception {
		if (null == dto.getDealType()) {
			dataMsg.failed("传入参数值“交易类型”为空");
			logger.error("传入参数值“交易类型”为空");
			return dataMsg;
		}
		// String dealCodes = this.getParameterString("dealCodes");
		String packageRule = this.getParameterString("packageRule");
		String cooperorgCode = dto.getCooperorgCode();
		String isFinish = this.getParameterString("isFinish");//是否是铜板街完成操作
		String planId = dto.getPlanId();//募集计划id

		try {
			
			//通过合约号获取合约相关信息
			ContractAllDto contractAllDto = contractService.getContractAllInfo(dto.getContractCode());
			
			//获取合约中是否上传影像状态
			String isUploadImage = "";
			if(contractAllDto!=null){
				isUploadImage = contractAllDto.getCdto().getIsUploadImage();
			}
			
			Map<String, Object> dealParams = new HashMap<String, Object>();
			String dealCode = dto.getDealCode();
			dealParams.put("dealCode", dealCode);
			DealDto dealList = dealService.getDealStream(dealParams);
			String eachType = "";
			if(dealList!=null){
				eachType = dealList.getLoanEachStatus();
			}
			
			// 保存交易
			dto = (DealDto) super.initDto(dto);
			 if("Y".equals(isFinish)){
				 dto.setCooperativeAgencyDealStatus(CimsConstant.DEAL_STATUS_FINISH);// 交易完成
			 }else{
				 dto.setCooperativeAgencyDealStatus(CimsConstant.DEAL_STATUS_CREATE);// 新建的状态
			 }
			
			
			if (CimsConstant.DEAL_TYPE_SECOND_PURCHASE.equals(dto.getDealType())) {
				dto.setLoanEachStatus(null);
			}else if(CimsConstant.DEAL_TYPE_CREDIT_OUT.equals(dto.getDealType()) || CimsConstant.DEAL_TYPE_LOAN_OUT.equals(dto.getDealType())) {
				if(eachType==null){
					if(CimsConstant.IS_UPLOAD_IMAGE_FILES.equals(isUploadImage)){
						dto.setLoanEachStatus(CimsConstant.LOAN_EACH_STATUS_URL);
					}else if(CimsConstant.NO_UPLOAD_IMAGE_FILES.equals(isUploadImage)){
						dto.setLoanEachStatus(CimsConstant.LOAN_EACH_STATUS_SEND);
					}
				}else{
					dto.setLoanEachStatus(eachType);
				}
				
			}
			cooperorgDealService.updateTCMmCooperorgDeal(dto);
			
			
			// 如果交易类型：01-债权转让，09-二次购买， 更新债权明细包信息
			if (CimsConstant.DEAL_TYPE_CREDIT_OUT.equals(dto.getDealType())) {
				// 更新债权明细包信息
				dealService.updateCreditDetailPackgeName(dto);
				if(CimsConstant.IS_UPLOAD_IMAGE_FILES.equals(isUploadImage)){
					dto.setLoanEachStatus(CimsConstant.LOAN_EACH_STATUS_URL);// 交易保存成功
					dealService.updateCreditDetailEachType(dto);//更新明细表状态
					springContextUtils.getBean(AddWaitDealQueueService.class).add(dto.getDealCode(), null);
				}else if(CimsConstant.NO_UPLOAD_IMAGE_FILES.equals(isUploadImage)){
					dto.setLoanEachStatus(CimsConstant.LOAN_EACH_STATUS_SEND);//上传影像资料完毕
					dealService.updateCreditDetailEachType(dto);//更新明细表状态
				}
				
			} else if (CimsConstant.DEAL_TYPE_SECOND_PURCHASE.equals(dto.getDealType())){
				// 更新债权明细包信息
				dealService.updateCreditDetailPackgeName(dto);
				
			}else if (CimsConstant.DEAL_TYPE_LOAN_OUT.equals(dto.getDealType())) {
				if (CimsConstant.PACKAGE_RULE_B.equals(packageRule)) {
					// 按照账单日的规则更新贷款明细包信息
					dealService.updateLoanDetailPackgeNameByBill(dto);
				} else {
					// 更新贷款明细包信息
					dealService.updateLoanDetailPackgeName(dto);
					if(CimsConstant.IS_UPLOAD_IMAGE_FILES.equals(isUploadImage)){
						dto.setLoanEachStatus(CimsConstant.LOAN_EACH_STATUS_URL);// 交易保存成功
						dealService.updateLoanDetailEachType(dto);//更新明细表状态
						springContextUtils.getBean(AddWaitDealQueueService.class).add(dto.getDealCode(), null);
					}else if(CimsConstant.NO_UPLOAD_IMAGE_FILES.equals(isUploadImage)){
						dto.setLoanEachStatus(CimsConstant.LOAN_EACH_STATUS_SEND);//上传影像资料完毕
						dealService.updateLoanDetailEachType(dto);//更新明细表状态
						
					}
				}
			}

			if (CimsConstant.PACKAGE_RULE_B.equals(packageRule)) {
				dealService.insertCreditPackageByBillDay(dto);
			} else {
				TCMmCreditPackageDTO creditPackageDTO = creditRightService.getCreditPackageForUnique(dto.getCooperorgCode(),
						dto.getCreditPackageName(), dto.getContractCode());
				if (null == creditPackageDTO) {
					// 保存包信息
					creditPackageDTO = new TCMmCreditPackageDTO();
					creditPackageDTO.setCooperorgCode(dto.getCooperorgCode());// 机构编号
					creditPackageDTO.setContractCode(dto.getContractCode());// 合约编号
					creditPackageDTO.setCreditPackageName(dto.getCreditPackageName());// 包号
					creditPackageDTO.setBillDate(dto.getBillDate());
					creditPackageDTO.setBillDateEnd(dto.getBillDateEnd());
					creditPackageDTO.setRepayType(dto.getRepayType());
					creditPackageService.insertTCMmCreditPackage(creditPackageDTO);
				}
			}
			//如果完成按钮
             if("Y".equals(isFinish)){
				if("TBJ".equals(cooperorgCode)){
					/**
					 * 调用service方法 修改交易状态 和募集状态 并发送通知
					 */
					if(SimpleStringUtils.hasText(planId)){
						raisePlanService.updateCooperorgDealAndRaisePlan(planId,dto);
					}
				}else{
					// 调用 《进件调配完成通知》
					dealService.doSendCooperorgNotice(dto);
				}
			}
			dataMsg = super.initDataMsg(dataMsg);
			dataMsg.setMsg("成功");
			dataMsg.setData(this.makeJSONData(dto.getId()));
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("执行方法saveCooperorgDeal异常：", ExceptionUtils.getStackTraceAsString(e));
			throw new Exception(e.getMessage());
		}
		return dataMsg;
	}
	
	/**
	 * 
	 * @Description 推送铜板街贷款信息
	 * @param request
	 * @param dto
	 * @param dataMsg
	 * @return   
	 * DataMsg  
	 * @throws
	 * @author zhangmi
	 * @date 2015-10-9
	 */
	@RequestMapping(value = "/doSend")
	@ResponseBody
	public  DataMsg doSend(HttpServletRequest request, DealDto dto, @ModelAttribute DataMsg dataMsg) throws Exception{
		try {
			if(!SimpleStringUtils.hasText(dto.getPlanId())){
				dataMsg.setStatus("N");
				dataMsg.failed("传入参数值“募集编号”为空");
				logger.error("传入参数值“募集编号”为空");
				return dataMsg;
			}
			//验证是否可以推送
			if(!tBJLoanService.checkToWaitSend(dataMsg,dto.getPlanId())){
				return dataMsg;
			}
			//推送
			tBJLoanService.updateLoanToWaitSend(dto.getPlanId());
			dataMsg.setStatus("Y");
			dataMsg.setMsg("贷款审批通过推送成功！");
		} catch (Exception e) {
			dataMsg.setMsg("贷款审批通过推送失败！");
			dataMsg.setStatus("N");
			dataMsg.failed(e.getMessage());
			logger.error("执行方法doSend异常：", e);
			throw new Exception(e.getMessage());
		}
		return dataMsg;
	}
	
	
	/**
	 * 获得债权包列表，参数为机构编号、合约编号(操作债权包表),显示的是债权明细为已转让的包列表
	 * 
	 * @param request
	 * @param response
	 * @param result
	 * @throws Exception
	 */
	@RequestMapping(value = "/getPackageList")
	@ResponseBody
	public DataMsg getPackageList(HttpServletRequest request, TCMmCreditPackageDTO dto, @ModelAttribute DataMsg dataMsg) throws Exception {
		Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("pagType", this.getParameterString("pagType"));
		searchParams.put("dto", dto);
		List<TCMmCreditPackageDTO> list = dealService.searchTCMmCreditPackage(searchParams);
		dataMsg.setData(list);
		return dataMsg;
	}

	/**
	 * 查询条件为合作机构、合约编号的查询列表，做债权交易的包下拉列表使用
	 * 
	 * @Title getPackageListByAll
	 * @Description TODO
	 * @param request
	 * @param dto
	 * @param dataMsg
	 * @return
	 * @throws Exception
	 *             DataMsg
	 * @author lizhiqiang
	 * @date 2015-4-17-下午4:48:13
	 * @update
	 * @throws
	 */
	@RequestMapping(value = "/getPackageListByAll")
	@ResponseBody
	public DataMsg getPackageListByAll(HttpServletRequest request, TCMmCreditPackageDTO dto, @ModelAttribute DataMsg dataMsg) throws Exception {
		Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("pagType", this.getParameterString("pagType"));
		searchParams.put("dto", dto);
		List<TCMmCreditPackageDTO> list = creditPackageService.searchTCMmCreditPackage(searchParams);
		dataMsg.setData(list);
		return dataMsg;
	}

	/**
	 * @author zhuwenbin
	 * @description:贷款导出报盘文件
	 * @date 2015-02-09 13:58:10
	 * @param request
	 * @param pageData
	 * @return
	 * @throws
	 */
	@RequestMapping(value = "/exportBpFile")
	@ResponseBody
	public DataMsg exportBpFile(HttpServletRequest request, HttpServletResponse response, @ModelAttribute DataMsg dataMsg) {

		String dealcode = (String) this.getParameter("dealCode");
		if (dealcode == null || "".equals(dealcode)) {
			dataMsg.setMsg("导出失败，交易流水号为空");
			return dataMsg;
		}
		dataMsg = super.initDataMsg(dataMsg);
		OutputStream out = null;
		try {
			TCMmLoanDetailDTO dto = new TCMmLoanDetailDTO();
			dto.setDealCode(dealcode);
			Map<String, Object> searchParams = new HashMap<String, Object>();
			searchParams.put("dto", dto);
			// 查询贷款明细列表
			List<LoanDetailDto> list = loanDealService.getDealDetailByLoanListForExport(searchParams);
			// 获取报盘流水号
			String bpfileNo = csysAssistimpl.getBizNo(CimsConstant.BIZNO_TYPE_BPFILE);
			List<Object> dfdtoList = convertDTO(list);
			// 获取报盘文件名称
			String fileFullName = getBpFileName(bpfileNo);
			// 设置response参数，可以打开下载页面
			response.reset();
			response.setContentType("application/x-download;charset=utf-8");
			response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileFullName.toString().getBytes(), "iso-8859-1"));
			out = response.getOutputStream();
			fileOperImpl.createBPFile(dfdtoList, out, CimsConstant.SEPARATOR_COMMA);
			out.flush();
			dataMsg.setMsg("导出成功");
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("执行方法exportBpFile异常：", ExceptionUtils.getStackTraceAsString(e));
			throw new CimsException(e.getMessage());
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					ExceptionUtils.getStackTraceAsString(e);
				}
			}
		}
		return dataMsg;
	}

	/**
	 * 组装报盘文件名称
	 * 
	 * @param bpfileNo
	 * @return
	 */
	public String getBpFileName(String bpfileNo) {
		StringBuffer bpFileName = new StringBuffer();
		String batchno = bpfileNo.substring(11);
		String commitDate = bpfileNo.substring(2, 10);
		// 商户ID
		bpFileName.append(PropertyUtil.get("local.merchantid"));
		bpFileName.append(CimsConstant.UNDERLINE);
		// 代付标志
		bpFileName.append(CimsConstant.DFFLAG);
		// 版本号
		bpFileName.append(CimsConstant.FILE_VERSION_02);
		// 提交日期
		bpFileName.append(commitDate);
		bpFileName.append(CimsConstant.UNDERLINE);
		// bpFileName.append(CimsConstant.DFFLAG);
		// 序号
		bpFileName.append(batchno);
		// 文件类型
		bpFileName.append(CimsConstant.FILE_TYPE_TXT);
		return bpFileName.toString();
	}

	/**
	 * 贷款明细dto装化为代付dto
	 * 
	 * @param list
	 * @return
	 */
	public List<Object> convertDTO(List<LoanDetailDto> list) {
		List<Object> dfdtoList = new ArrayList<Object>(list.size());
		int serno = 0;
		DfHzContentDto dfhz = new DfHzContentDto();
		long totalAmount = 0l;
		for (LoanDetailDto dto : list) {
			serno++;
			Df02FileDto dfdto = new Df02FileDto();
			dfdto.setSerNo(String.valueOf(dto.getId()));
			dfdto.setUserCode(dto.getCustCode());
			dfdto.setBankCode(dto.getLoanBankCode());
			dfdto.setAcccNoType(CimsConstant.accType_00);
			dfdto.setAccountNo(dto.getLoanAcctNo());
			dfdto.setAccountName(dto.getLoanAcctName());
			dfdto.setAmount(dto.getLoanAmount().toString());
			dfdto.setPapersType(dto.getCardType());
			dfdto.setPapersNo(dto.getCardId());
			// 商户自定义用户号
			dfdto.setUserdefinedNo(dto.getContractNo());
			// 增加信托计划代码@@合同编号@@身份证号码，例如：JY_MSXT1@@2014091211032014@@11010319880909004X
			StringBuffer note = new StringBuffer();
			note.append(PropertyUtil.get("local.jy_msxt_code"));
			note.append(CimsConstant.SEPARATOR_AT);
			note.append(dto.getContractNo());
			note.append(CimsConstant.SEPARATOR_AT);
			note.append(dto.getCardId());
			dfdto.setNote(note.toString());
			dfdtoList.add(dfdto);
			// 统计交易金额
			totalAmount += (dto.getLoanAmount().longValue());
		}
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
		dfhz.setTotalAmount(String.valueOf(totalAmount));
		dfhz.setTotalNum(String.valueOf(serno));
		dfhz.setDsFlag(CimsConstant.DFFLAG);
		dfhz.setCommitDate(formatter.format(new Date()));
		// 商户ID属性暂时写死
		dfhz.setMerchantId(PropertyUtil.get("local.merchantid"));
		// 业务类型暂时写死
		dfhz.setBusinessType(PropertyUtil.get("local.payment_type_other"));
		// 将汇总信息放入第一条
		dfdtoList.add(0, dfhz);
		return dfdtoList;
	}

	/**
	 * 贷款导入回盘信息
	 * 
	 * @param request
	 * @param response
	 * @param dataMsg
	 * @return
	 */
	@RequestMapping(value = "/importHpFile")
	@ResponseBody
	public DataMsg ImportHpFile(HttpServletRequest request, HttpServletResponse response, @ModelAttribute DataMsg dataMsg) {
		String dealcode = (String) this.getParameter("dealCode");
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
		FileItem fileItems = file.getFileItem();
		InputStream in = null;
		try {
			in = fileItems.getInputStream();
			List<Object> objList = fileOperImpl.analyHPFileByStream(in, CimsConstant.SEPARATOR_COMMA, 21, DfHzContentDto.class, Df02FileDto.class);
			int totlanum = objList.size() - 1;
			DfHzContentDto hz = (DfHzContentDto) objList.get(0);
			if (totlanum == Integer.parseInt(hz.getTotalNum())) {

				Df02FileDto filedto = (Df02FileDto) objList.get(1);
				String contractNo = filedto.getUserdefinedNo();
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("contractNo", contractNo);
				List<String> dealcodeList = loanDealService.getLoanDealCodeByContractNo(paramMap);
				if (dealcodeList.size() > 1) {
					dataMsg.setMsg("导入失败,合同号对应交易流水号有误");
					dataMsg.setStatus("error");
				} else {
					// 判断该笔交易是否已导入回盘信息
					String hpdealcode = dealcodeList.get(0);
					if (!dealcode.equals(hpdealcode)) {
						dataMsg.setMsg("导入失败,回盘文件交易流水号有误");
						dataMsg.setStatus("error");
						return dataMsg;
					}
					Map<String, Object> searchParams = new HashMap<String, Object>();
					TCMmCooperorgDealDTO dto = new TCMmCooperorgDealDTO();
					dto.setDealCode(hpdealcode);
					searchParams.put("dto", dto);
					List<TCMmCooperorgDealDTO> dtolist = cooperorgDealService.searchTCMmCooperorgDeal(searchParams);
					if (dtolist.size() > 0) {
						dto = dtolist.get(0);
						//if (CimsConstant.LOAN_EACH_STATUS_FUNDOUT_WIN.equals(dto.getLoanEachStatus())) {
//							dataMsg.setMsg("导入失败，该回盘文件已导入");
//							dataMsg.setStatus("error");
//							return dataMsg;
						//}
					}
					// 修改贷款明细状态
					loanDealService.updateTCMmLoanDetailLoanStatus(objList, dto);
					//loanImpl.updateLoanEachStatusByDealCode(dealcode, CimsConstant.LOAN_EACH_STATUS_FUNDOUT_WIN);
				}
			} else {
				dataMsg.setMsg("导入失败,文件格式有误");
				dataMsg.setStatus("error");
			}
		} catch (Exception e) {
			dataMsg.setMsg("导入失败,文件格式有误");
			dataMsg.setStatus("error");
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					ExceptionUtils.getStackTraceAsString(e);
				}
			}
		}
		return dataMsg;
	}

	/**
	 * 根据债权包查询债权明细
	 * 
	 * @param request
	 * @param response
	 * @param result
	 */
	@RequestMapping(value = "/getDealDetailByPackage")
	@ResponseBody
	public DataMsg getDealDetailByPackage(HttpServletRequest request, CreditDetailQueryDto dto, @ModelAttribute DataMsg dataMsg) {
		Map<String, Object> searchParams = new HashMap<String, Object>();
		try {
			dto.setPackageNum(ExportController.ExportUtil.convertCharset(dto.getPackageNum()));
			// 设置异常债权类型
			String abnormalSettle = this.getParameterString("abnormalSettle");
			if (abnormalSettle != null && abnormalSettle.length() > 0) {
				String[] types = abnormalSettle.split(",");
				List<String> planStatusList = new ArrayList<String>();
				for (String type : types) {
					planStatusList.add(type);
				}
				dto.setPlanStatusList(planStatusList);
			}
			searchParams.put("dto", dto);
			QueryReqBean params = new QueryReqBean();
			params.setSearchParams(searchParams);
			PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
			params.setPageParameter(pageInfo);
			List<CreditDetailDto> creditRightList = settleCreditService.searchCreditDetailForSettleByPaging(params.getSearchParams());
			dataMsg.setData(creditRightList);
			dataMsg.setTotalRows(pageInfo.getTotalCount());
		} catch (Exception e) {
			if (!CimsConstant.NULL_FLAG.equals(dto.getPackageNum())) {
				dataMsg.failed(e.getMessage());
			}
		}
		return dataMsg;
	}
	
	/**
	 * 根据二次购买流水号-查询对应月还，异常的债权
	 * @Title queryMonthCreditDetail
	 * @Description TODO
	 * @param request
	 * @param dto
	 * @param dataMsg
	 * @return 
	 * DataMsg 
	 * @author zhangmi
	 * @date 2016-8-5-下午4:40:51
	 * @update 
	 * @throws
	 */
	@RequestMapping(value = "/queryMonthCreditDetail")
	@ResponseBody
	public DataMsg queryMonthCreditDetail(HttpServletRequest request,DealDto dto,  @ModelAttribute DataMsg dataMsg) {
		try {
			// 设置异常债权类型
			dataMsg = super.initDataMsg(dataMsg);
			QueryReqBean params = new QueryReqBean();
			params.setSearchParams(SearchParamUtil.getSearchParam(dto));
			PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
			params.setPageParameter(pageInfo);
			dataMsg.setData(dealService.getSecondMonthCreditDetails(params.getSearchParams()));
			dataMsg.setTotalRows(pageInfo.getTotalCount());
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("查询二次购买月还信息失败：", ExceptionUtils.getStackTraceAsString(e));
		}
		return dataMsg;
	}
	/**
	 * 
	 */
	@RequestMapping(value = "/loandDealSettle")
	@ResponseBody
	public DataMsg loandDealSettle(HttpServletRequest request,DealDto dto,  @ModelAttribute DataMsg dataMsg) {
		try {
			dealService.doLoanDealSettle(dto);
			dataMsg.setMsg("发送成功!");
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("发送贷款转出结算申请失败：", ExceptionUtils.getStackTraceAsString(e));
		}
		return dataMsg;
	}
	/**
	 * 
	 * @Title finishDeal
	 * @Description TODO
	 * @return 
	 * DateMsg 
	 * @author lizhiqiang
	 * @date 2016-12-27-下午3:09:22
	 * @update 
	 * @throws
	 */
	@RequestMapping(value = "/finishDeal")
	@ResponseBody
	public DataMsg finishDeal(HttpServletRequest request,DealDto dto,  @ModelAttribute DataMsg dataMsg){
		try {
			// 调用 《进件调配完成通知》
			dealService.doSendCooperorgNoticeByCredit(dto);
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("发送债权调配完成通知失败："+ExceptionUtils.getStackTraceAsString(e));
		}
		return dataMsg;
	}
	/**
	 * 确认转让交易，发送核心债权确认结果
	 * @Title confirmDeal
	 * @Description TODO
	 * @param request
	 * @param dto
	 * @param dataMsg
	 * @return 
	 * DataMsg 
	 * @author lizhiqiang
	 * @date 2016-12-28-下午2:32:49
	 * @update 
	 * @throws
	 */
	@RequestMapping(value = "/confirmDeal")
	@ResponseBody
	public DataMsg confirmDeal(HttpServletRequest request,DealDto dto,  @ModelAttribute DataMsg dataMsg){
		try {
			// 调用 《进件调配完成通知》
			dealService.doconfirmCreditDeal(dto);
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("发送债权调配完成通知失败："+ExceptionUtils.getStackTraceAsString(e));
		}
		return dataMsg;
	}
	

}